const app = getApp()
var liveroom = require('../../components/mlvb-live-room/mlvbliveroomcore.js');

const {
  upLoadImg,
  getNewUserInfo,
  getUserSig
} = require('../../api/common.api')

const {
  startLiveApi
} = require('../../api/live-api')

const {
  getWalletInfo
} = require('../../api/user-center-api')
import {
  chargeList
} from '../../utils/data'


Page({

  /**
   * 页面的初始数据
   */
  data: {
    roomName: "直播间标题自定义", // 房间名称
    userName: '', // 用户名称
    userID: '', // 用户ID
    userAvatar: '',
    // pureAudio: false, // 是否音频开播
    cover: 'https://cebeiqiniu.nmhywl.cn/image/c85ca67f56a800ad72729a004a3d0592.png',
    chargeOfMinute: 0, // 连麦收费金额
    chargeList: chargeList, // 充值列表
    showSetCharge: false,
    curNewUserInfo: null, // 当前的用户信息
    showLiveTypeModal: false,

    tapTime: '', // 防止两次点击操作间隔太快
    headerHeight: app.globalData.headerHeight,
    statusBarHeight: app.globalData.statusBarHeight,

    // isGetLoginInfo: false, // 是否已经获取登录信息
    // firstshow: true, // 第一次显示页面



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let _this = this;
    // this.getWalletInfo()
    // getUserSig().then(res => {

    //   _this.setData({
    //     userName: res.user_name,
    //     userID: res.userid
    //   })

    //   // 登录roomService
    //   var loginInfo = {
    //     sdkAppID: res.sdk_app_id,
    //     userID: res.userid,
    //     userSig: res.user_sig,
    //     userName: res.user_name,
    //     userAvatar: res.user_avatar
    //   }
    //   // console.log(res, 'userInfo Sig')
    //   //MLVB 登录
    //   liveroom.login({
    //     data: loginInfo,
    //     success: function (ret) {

    //       _this.data.firstshow = false;
    //       _this.data.isGetLoginInfo = true;
    //       wx.hideLoading();
    //     },
    //     fail: function (ret) {
    //       //登录失败
    //       _this.data.isGetLoginInfo = false;
    //       wx.hideLoading();
    //       wx.showModal({
    //         title: '提示',
    //         content: ret.errMsg,
    //         showCancel: false,
    //         complete: function () {
    //           wx.navigateBack({});
    //         }
    //       });
    //     }
    //   });
    // })

  },
  /**
   * 直播背景更新
   */
  upLoadBgImg() {
    let _this = this;
    upLoadImg((path) => {
      _this.setData({
        cover: path
      })
    })
  },
  /**
   * 直播房间标题更新
   */
  onRoomTitleInput(e) {

    this.setData({
      roomName: e.detail.value
    })


  },
  /**
   * 检查用户当前的认证状态  
   * 0:普通用户 1:审核中2：已认证 3:审核未通过
   */
  checkUserStatus(status) {
    switch (status) {
      case 0:
        wx.showModal({
          title: '提示',
          content: '请先认证你的个人信息， 然后才能开启相关服务。',
          cancelColor: '#576B95',
          confirmText: '立即认证',
          cancelText: '取消',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/attestation/index',
              })
            } else if (res.cancel) {
              wx.switchTab({
                url: '/pages/index/index',
              })

            }
          }
        })
        break;
      case 1:
        wx.showModal({
          title: '提示',
          content: '您已经提交审核，请耐心等待审核完成。',
          showCancel: false,
          confirmText: '我知道了',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/user-center/index',
              })
            }
          }
        })
        break;
      case 3:
        wx.showModal({
          title: '提示',
          content: '您的认证审核未通过，请重新提交一下您的认证资料。',
          showCancel: false,
          confirmText: '重新认证',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/attestation/index',
              })
            }
          }
        })
        break;
    }
  },
  /**
   * 显示连麦收费
   */
  onShowSetCharge() {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showSetCharge: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  /**
   * 隐藏连麦收费框
   */
  onHideSetCharge() {
    // 隐藏遮罩层
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showSetCharge: false
      })
    }.bind(this), 200)
  },
  /**
   * 设置连麦收费金额
   */
  onSetChargeNum(e) {
    this.setData({
      chargeOfMinute: e.currentTarget.dataset.yb
    })
  },
  /**
   * 跳转协议
   */
  goAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let _this = this;
    // 获取当前用户信息
    getUserSig().then(res => {

      _this.setData({
        userName: res.user_name,
        userID: res.userid,
        userAvatar: res.user_avatar
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    getNewUserInfo().then(res => {
      _this.setData({
        roomName: `${res.nickname}的直播间`,
        curNewUserInfo: res,
      })
      _this.checkUserStatus(res.status)
    })

    // 登录roomService
    getUserSig().then(res => {
      let _this = this,
        loginInfo = {
          sdkAppID: res.sdk_app_id,
          userID: res.userid,
          userSig: res.user_sig,
          userName: res.user_name,
          userAvatar: res.user_avatar
        }
      liveroom.login({
        data: loginInfo,
        success: function (ret) {
          _this.setData({
            roomServiceIsLogin: true,
            userID: res.userid,
            userName: res.user_name,
            userAvatar: res.user_avatar
          })
          app.globalData.roomServiceIsLogin = true;
        },
        fail: function (ret) {
          //登录失败
          _this.data.roomServiceIsLogin = false;
          wx.showModal({
            title: '提示',
            content: ret.errMsg,
            showCancel: false,
            complete: function () {
              wx.navigateBack({});
            }
          });
        }
      });
    })
    console.log(app.globalData.roomServiceIsLogin, '登录了吗？')
  },
  /**
   * 开始直播
   * 选择直播方式 语音 or 视频直播 弹层
   */
  onStartLive() {
    // 当前用户已认证
    if (this.data.curNewUserInfo.status == 2) {
      // 显示遮罩层
      var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
      })
      this.animation = animation
      animation.translateY(300).step()
      this.setData({
        liveAnimationData: animation.export(),
        showLiveTypeModal: true
      })
      setTimeout(function () {
        animation.translateY(0).step()
        this.setData({
          liveAnimationData: animation.export()
        })
      }.bind(this), 200)
    } else {
      wx.showToast({
        title: '您未认证或者认证失败',
        duration: 1500,
        icon: 'none'
      })
    }
  },
  /**
   * 隐藏设置直播类型弹框
   */
  onHideSetLiveType() {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      liveAnimationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        liveAnimationData: animation.export(),
        showLiveTypeModal: false
      })
    }.bind(this), 200)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },
  /**
   *  开始直播 跳转直播页
   * 
   * @params 1:语音直播 2:视频直播
   */

  onStartLiveType(event) {
    let _this = this,
      pureAudio = event.currentTarget.dataset.type == 2 ? false : true,

      nowTime = new Date(); // 防止两次点击操作间隔太快

    if (nowTime - this.data.tapTime < 1000) {
      return;
    }

    if (/[<>*{}()^%$#@!~&= ]/.test(_this.data.roomName)) {
      wx.showModal({
        title: '提示',
        content: '名称不能为空或包含特殊字符',
        showCancel: false
      });
      return;
    };

    let params = {
      title: _this.data.roomName,
      cover: _this.data.cover,
      type: event.currentTarget.dataset.type,
      diamonds: _this.data.chargeOfMinute,
    }
    startLiveApi(params).then(res => {
      console.log(res, 'res')
      let url = `./live-room/index?type=create&roomName=${res.title}&userName=${_this.data.userName}&pureAudio=${pureAudio}&roomID=${res.id}&cover=${res.cover}&userID=${_this.data.userID}&diamonds=${_this.data.chargeOfMinute}&avatar=${_this.data.userAvatar}`
      wx.redirectTo({
        url: url,
        success() {
          wx.showToast({
            title: '进入房间',
            icon: 'success',
            duration: 1000
          });
          _this.onHideSetLiveType();
        }
      });
    })

    // getUserSig().then(res => {

    //   _this.setData({
    //     userName: res.user_name,
    //     userID: res.userid,
    //     avatar: res.user_avatar
    //   })

    //   // 登录roomService
    //   var loginInfo = {
    //     sdkAppID: res.sdk_app_id,
    //     userID: res.userid,
    //     userSig: res.user_sig,
    //     userName: res.user_name,
    //     userAvatar: res.user_avatar
    //   }
    //   // console.log(res, 'userInfo Sig')
    //   //MLVB 登录
    //   liveroom.login({
    //     data: loginInfo,
    //     success: function (ret) {
    //       let date = new Date();
    //       let params = {
    //         title: _this.data.roomName + date.getHours() + date.getMinutes(),
    //         cover: _this.data.cover,
    //         type: event.currentTarget.dataset.type,
    //         diamonds: _this.data.chargeOfMinute,
    //       }
    //       // console.log(params, 'params^^^^^^^^')
    //       startLiveApi(params).then(res => {
    //         console.log(res, 'res')
    //         let url = `./live-room/index?type=create&roomName=${res.title}&userName=${_this.data.userName}&pureAudio=${pureAudio}&roomID=${res.id}&cover=${res.cover}&userID=${_this.data.userID}&diamonds=${_this.data.chargeOfMinute}&avatar=${_this.data.avatar}`
    //         wx.redirectTo({
    //           url: url,
    //           success() {
    //             wx.showToast({
    //               title: '进入房间',
    //               icon: 'success',
    //               duration: 1000
    //             });
    //             _this.onHideSetLiveType();
    //           }
    //         });

    //       })

    //       _this.data.firstshow = false;
    //       _this.data.isGetLoginInfo = true;
    //       wx.hideLoading();
    //     },
    //     fail: function (ret) {
    //       //登录失败
    //       _this.data.isGetLoginInfo = false;
    //       wx.hideLoading();
    //       wx.showModal({
    //         title: '提示',
    //         content: ret.errMsg,
    //         showCancel: false,
    //         complete: function () {
    //           wx.navigateBack({});
    //         }
    //       });
    //     }
    //   });
    // })

    // if (_this.data.isGetLoginInfo) {

    // } else {
    //   wx.showToast({
    //     title: 'roomService登录失败',
    //   })
    // }





    _this.setData({
      'tapTime': nowTime
    });


  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})